package com.ctbri.manage.file.controller;

import com.alibaba.fastjson.JSONObject;
import com.ctbri.manage.file.model.DataAlignSource;
import com.ctbri.manage.file.model.DataAlignTask;
import com.ctbri.manage.file.model.RestfulResult;
import com.ctbri.manage.file.service.DataAlignSourceService;
import com.ctbri.manage.file.service.DataAlignTaskService;
import com.mysql.cj.util.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.*;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.sql.Timestamp;
import java.util.UUID;


import org.springframework.core.env.Environment;

/**
 * ClassName:DataAlignTaskController
 * Package:com.ctbri.manage.file.controller
 * Description:
 * 与数据对齐工具对接接口
 *
 * @Author:qs
 * @Create:2023/7/5
 * @Version：1.0
 */
@RestController
@RequestMapping("/api/dataAlignTask")
public class DataAlignTaskController {

    @Resource
    private RestTemplate restTemplate;
    @Resource
    private DataAlignTaskService dataAlignTaskService;

    @Resource
    private DataAlignSourceService dataAlignSourceService;

    @Resource
    private Environment env;

    /**
     * Logger实例
     */
    static final Logger logger = LoggerFactory.getLogger(DataAlignTaskController.class);

    /***
     * Description:
     * 提交两表（基准表与目标表）对齐任务
     * @param json
     * @return
     */
/*
    @PostMapping(value = "/submitAlignTaskByTable", produces = "application/json;charset=UTF-8")
    public RestfulResult<?> submitAlignTaskByTable(JSONObject json) {

        //logger.info("开始———————>提交两表（基准表与目标表）对齐任务接口：接收界面传入参数值为：" + json.toString());
        if (json == null) {
            return new RestfulResult<>(0, "Received parameter is empty.");
        }
        Integer code = 0;
        String msg = "按表调用提交对齐任务接口失败";
        try {
            // 1-设置请求头，指定Content-Type为application/json
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);

            // 2-整理接口传输参数
            JSONObject httpJSONObject = new JSONObject();
            //随机生成32位主键
            String primaryKey = UUID.randomUUID().toString().replace("-", "").toLowerCase();
            httpJSONObject.put("task_id", primaryKey);

            */
    /*

            //基准表处理方式(local：本地；remote：远程)
            httpJSONObject.put("input_type1", json.get("input_type1").toString());
            //基准表数据库类型（postgresql；sqlite;csv）
            httpJSONObject.put("input_src1", json.get("input_src1").toString());

            //基准数据源id
            Integer sourceBaseId = Integer.valueOf(json.get("source_base_id").toString());
            //根据基准数据源id获取数据源信息
            DataAlignSource dataAlignBaseSource = dataAlignSourceService.selectDataAlignSourceBySourceId(sourceBaseId, 1);
            String sourceBaseContent = dataAlignBaseSource.getSourceContent();
            JSONObject jsonBaseSource = JSONObject.parseObject(sourceBaseContent);
            httpJSONObject.put("input_database1", jsonBaseSource.get("input_database").toString());
            httpJSONObject.put("input_table1", jsonBaseSource.get("input_table").toString());
            httpJSONObject.put("user1", jsonBaseSource.get("user").toString());
            httpJSONObject.put("passwd1", jsonBaseSource.get("passwd").toString());
            httpJSONObject.put("host1", jsonBaseSource.get("host").toString());
            httpJSONObject.put("port1", jsonBaseSource.get("port").toString());
            if (null == json.get("save_limit1").toString()) {
                json.put("save_limit1", 1000);
            }
            httpJSONObject.put("save_limit1", Integer.valueOf(json.get("save_limit1").toString()));

            */
/*

            //目标表处理方式(local：本地；remote：远程)
            httpJSONObject.put("input_type2", json.get("input_type2").toString());
            //目标表数据库类型（postgresql；sqlite;csv）
            httpJSONObject.put("input_src2", json.get("input_src2").toString());
            //目标数据源ID
            Integer sourceTargetId = Integer.parseInt(json.get("source_target_id").toString());
            DataAlignSource dataAlignTargetSource = dataAlignSourceService.selectDataAlignSourceBySourceId(sourceTargetId, 1);
            String sourceTargetContent = dataAlignTargetSource.getSourceContent();
            JSONObject jsonTargetSource = JSONObject.parseObject(sourceTargetContent);

            httpJSONObject.put("input_database2", jsonTargetSource.get("input_database").toString());
            httpJSONObject.put("input_table2", jsonTargetSource.get("input_table").toString());
            httpJSONObject.put("user2", jsonTargetSource.get("user").toString());
            httpJSONObject.put("passwd2", jsonTargetSource.get("passwd").toString());
            httpJSONObject.put("host2", jsonTargetSource.get("host").toString());
            httpJSONObject.put("port2", jsonTargetSource.get("port").toString());
            if (null == json.get("save_limit2").toString()) {
                json.put("save_limit2", 1000);
            }
            httpJSONObject.put("save_limit2", Integer.valueOf(json.get("save_limit2").toString()));

            // 设置接口请求参数
//            HttpEntity<String> request = new HttpEntity<>(httpJSONObject.toString(), headers);
//            logger.info("准备提交中———————>提交两表（基准表与目标表）对齐任务接口：请求服务端json值为：" + httpJSONObject.toString());
//            // 发送POST请求
//            String url = env.getProperty("api.submit-alignTask-table-url");
        //   ResponseEntity<String> response = restTemplate.postForEntity(url, request, String.class);

            // 处理响应结果
//            if (null != response && !StringUtils.isNullOrEmpty(response.getBody())) {
//                JSONObject resJsonObj = JSONObject.parseObject(response.getBody().toString());
//                code = Integer.valueOf(resJsonObj.get("code").toString());
//                msg = resJsonObj.get("msg").toString();
//
//                //请求成功后，将任务信息保存到数据对齐任务表（mdm_data_align_task）中
//                if (code == 1) {
//                    DataAlignTask dataAlignTask = JSONObject.toJavaObject(json, DataAlignTask.class);
//                    dataAlignTask.setTaskId(primaryKey);
//                    dataAlignTask.setSubmitTime(new Timestamp(System.currentTimeMillis()));
//                    httpJSONObject.remove("passwd1");
//                    httpJSONObject.remove("passwd2");
//                    dataAlignTask.setTaskDetail(httpJSONObject.toString());
//                    dataAlignTaskService.insertSelective(dataAlignTask);
//                }
//                logger.info("结束———————>提交两表（基准表与目标表）对齐任务接口：服务端返回值为：" + response.getBody().toString());
//            } else {
//                msg = "提交数据到接口后，未得到响应消息";
//                logger.info("结束———————>提交两表（基准表与目标表）对齐任务接口：未接受到服务端返回值。");
//            }

        } catch (Exception e) {
//            code = 0;
//            msg = e.getMessage();
            throw new RuntimeException(e);
        }

        return new RestfulResult<>(code, msg);
    }
*/

    /***
     * Description:
     * 根据两文件（基准文件与目标文件）提交对齐任务
     * @param --json
     * @return
     */
 /*   @PostMapping(value = "/submitAlignTaskByFile")
    public RestfulResult<?> submitAlignTaskByFile(JSONObject json) {
        //logger.info("开始———————>根据两文件（基准文件与目标文件）提交对齐任务接口：接收界面传入参数值为：" + json.toString());
        if (json == null) {
            return new RestfulResult<>(0, "Received parameter is empty.");
        }
        Integer code = 0;
        String msg = "按文件调用提交对齐任务接口失败";
        try {
            // 1-设置请求头，指定Content-Type为application/json
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);

            //2-整理接口传输参数
            JSONObject httpJSONObject = new JSONObject();
            //随机生成32位主键
            String primaryKey = UUID.randomUUID().toString().replace("-", "").toLowerCase();
            httpJSONObject.put("task_id", primaryKey);

            *//***2-1整理基准表传输参数****//*
            //基准数据源id
            Integer sourceBaseId = Integer.valueOf(json.get("source_base_id").toString());
            //根据基准数据源id获取数据源信息
            DataAlignSource dataAlignBaseSource = dataAlignSourceService.selectDataAlignSourceBySourceId(sourceBaseId, 2);
            String sourceBaseContent = dataAlignBaseSource.getSourceContent();
            JSONObject jsonBaseSource = JSONObject.parseObject(sourceBaseContent);

            httpJSONObject.put("input_src1", jsonBaseSource.get("file_path").toString());
            httpJSONObject.put("delimiter1", jsonBaseSource.get("delimiter").toString());
            httpJSONObject.put("header1", jsonBaseSource.get("header").toString());

            *//***2-2整理目标表传输参数****//*
            //目标数据源id
            Integer sourceTargetId = Integer.valueOf(json.get("source_target_id").toString());
            //根据基准数据源id获取数据源信息
            DataAlignSource dataAlignTargetSource = dataAlignSourceService.selectDataAlignSourceBySourceId(sourceTargetId, 2);
            String sourceTargetContent = dataAlignTargetSource.getSourceContent();
            JSONObject jsonTargetSource = JSONObject.parseObject(sourceTargetContent);

            httpJSONObject.put("input_src2", jsonTargetSource.get("file_path").toString());
            httpJSONObject.put("delimiter2", jsonTargetSource.get("delimiter").toString());
            httpJSONObject.put("header2", jsonTargetSource.get("header").toString());

//            // 设置请求参数
//            HttpEntity<String> request = new HttpEntity<>(httpJSONObject.toString(), headers);
//            logger.info("准备提交中———————>根据两文件（基准文件与目标文件）提交对齐任务接口：请求服务端json值为：" + httpJSONObject.toString());
//
//            // 发送POST请求
//            String url = env.getProperty("api.submit-alignTask-file-url");
//            ResponseEntity<String> response = restTemplate.postForEntity(url, request, String.class);
//
//            // 处理响应结果
//            if (null != response && !StringUtils.isNullOrEmpty(response.getBody())) {
//                JSONObject resJsonObj = JSONObject.parseObject(response.getBody().toString());
//                code = Integer.valueOf(resJsonObj.get("code").toString());
//                msg = resJsonObj.get("msg").toString();
//
//                //请求成功后，将任务信息保存到数据对齐任务表（mdm_data_align_task）中
//                if (code == 1) {
//                    DataAlignTask dataAlignTask = JSONObject.toJavaObject(httpJSONObject, DataAlignTask.class);
//                    dataAlignTask.setInputType1("local");
//                    dataAlignTask.setInputType2("local");
//                    dataAlignTask.setSourceBaseId(sourceBaseId.toString());
//                    dataAlignTask.setSourceTargetId(sourceTargetId.toString());
//                    dataAlignTask.setSubmitTime(new Timestamp(System.currentTimeMillis()));
//                    dataAlignTask.setTaskDetail(httpJSONObject.toString());
//                    dataAlignTaskService.insertSelective(dataAlignTask);
//                }
//                logger.info("结束———————>根据两文件（基准文件与目标文件）提交对齐任务接口：服务端返回值为：" + response.getBody().toString());
//            } else {
//                msg = "提交数据到接口后，未得到响应消息";
//                logger.info("结束———————>根据两文件（基准文件与目标文件）提交对齐任务接口：未接受到服务端返回值。");
//            }

        } catch (Exception e) {
//            code = 0;
//            msg = e.getMessage();
            throw new RuntimeException(e);
        }
        return new RestfulResult<>(code, msg);
    }*/

    /**
     * Description:
     * 返回对齐匹配结果
     *
     * @param json
     * @return
     */
  /*  @PutMapping(value = "/alignMatchResults", produces = "application/json;charset=UTF-8")
    public RestfulResult<?> alignMatchResults(JSONObject json) {
       // logger.info("开始———————>返回对齐匹配结果接口：接收返回参数值为：" + json.toString());
        if (json == null) {
            return new RestfulResult<>(0, "Received parameter is empty");
        }
        Integer code = 0;
        String msg = "Failed to receive the result";
        try {
            JSONObject resJsonObj = JSONObject.parseObject(json.toString());
            DataAlignTask dataAlignTask = JSONObject.toJavaObject(resJsonObj, DataAlignTask.class);
            dataAlignTask.setUpdateTime(new Timestamp(System.currentTimeMillis()));
            dataAlignTaskService.updateByPrimaryKeySelective(dataAlignTask);
            code = 1;
            msg = "Successfully received the result";
        } catch (Exception e) {
//            msg = e.getMessage();
            throw new RuntimeException(e);
        }
        logger.info("结束———————>返回对齐匹配结果接口：返回对齐匹配结果已保存到mdm_data_align_task表中");
        return new RestfulResult<>(code, msg);
    }*/

    /**
     * Description:
     * 根据任务ID，查询对齐任务信息
     *
     * @param task_id
     * @return
     */
    @GetMapping(value = "/queryAlignTaskByTaskId/{task_id}")
    public RestfulResult<?> queryAlignTaskByTaskId(@PathVariable String task_id) {
        if ("".equals(task_id)) {
            return new RestfulResult<>(0, "taskId parameter is empty");
        }
        Integer code = 0;
        String msg = "调用查询对齐任务接口失败";
        JSONObject resJsonObj = null;
        try {
            // 设置请求头，指定Content-Type为application/json
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);

            // 发送POST请求
            String url = env.getProperty("api.query-alignTask-url");
//            url = url + "/" + task_id;
      /*      ResponseEntity<String> response = restTemplate.getForEntity(url, String.class);

            // 处理响应结果
            if (null != response && !StringUtils.isNullOrEmpty(response.getBody())) {
                resJsonObj = JSONObject.parseObject(response.getBody().toString());

                //将查询到的结果信息，更新到数据对齐任务表（mdm_data_align_task）中
                DataAlignTask dataAlignTask = JSONObject.toJavaObject(resJsonObj, DataAlignTask.class);
                dataAlignTask.setUpdateTime(new Timestamp(System.currentTimeMillis()));
                dataAlignTaskService.updateByPrimaryKeySelective(dataAlignTask);
                code = 1;
                msg = "成功查询到结果信息，并已保存到数据库中";
                logger.info("结束———————>根据任务ID，查询对齐任务信息接口：查询到结果值为：" + response.getBody().toString());
            } else {
                msg = "接口未返回查询到的任务信息";
                logger.info("结束———————>根据任务ID，查询对齐任务信息接口：未接受到服务端返回值。");
            }*/
        } catch (Exception e) {
//            code = 0;
//            msg = e.getMessage();
            throw new RuntimeException(e);
        }
        return new RestfulResult<>(code, msg, resJsonObj);
    }

    /**
     * Description:
     * 根据任务ID，停止对齐任务
     *
     * @param task_id
     * @return
     */
    @PutMapping(value = "/stopAlignTaskByTaskId/{task_id}")
    public RestfulResult<?> stopAlignTaskByTaskId(@PathVariable String task_id) {
       // logger.info("开始———————>根据任务ID，停止对齐任务接口：请求参数值为：" + task_id);
        if ("".equals(task_id)) {
            return new RestfulResult<>(0, "taskId parameter is empty");
        }
        Integer code = 0;
        String msg = "调用停止对齐任务接口失败";
       // JSONObject resJsonObj = null;
        try {
            // 设置请求头，指定Content-Type为application/json
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);

            // 发送PUT请求
//            String url = env.getProperty("api.stop-alignTask-url");
//            url = url + "/" + task_id;
//            HttpEntity<String> entity = new HttpEntity<>(null, headers);
//            ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.PUT, entity, String.class);
//
//            // 处理响应结果
//            if (null != response && !StringUtils.isNullOrEmpty(response.getBody())) {
//                resJsonObj = JSONObject.parseObject(response.getBody().toString());
//                code = Integer.valueOf(resJsonObj.get("code").toString());
//                msg = resJsonObj.get("msg").toString();
//
//                if (code == 1) { //服务端执行成功后，更新数据对齐任务表（mdm_data_align_task）
//                    DataAlignTask dataAlignTask = dataAlignTaskService.selectByPrimaryKey(task_id);
//                    //1-表示任务执行成功；2-表示任务执行失败；3-已删除
//                    dataAlignTask.setStatus(3);
//                    dataAlignTask.setMessage(msg);
//                    dataAlignTask.setUpdateTime(new Timestamp(System.currentTimeMillis()));
//                    //服务端停止该任务后，将往数据对齐任务表（mdm_data_align_task）删除此数据
//                    dataAlignTaskService.updateByPrimaryKeySelective(dataAlignTask);
//                }
//                logger.info("结束———————>根据任务ID，停止对齐任务接口：响应值为：" + response.getBody().toString());
//            } else {
//                msg = "接口未返回停止对齐任务信息";
//                logger.info("结束———————>根据任务ID，停止对齐任务接口：未接受到服务端返回值。");
//            }

        } catch (Exception e) {
//            code = 0;
//            msg = e.getMessage();
            throw new RuntimeException(e);
        }
        return new RestfulResult<>(code, msg);
    }


}
